import { Sprite } from './Sprite';
import { MagicSprite } from './MagicSprite';
import { sleep } from './utils';


//一秒有多少毫毫秒
const oneSecond = 1000.0;
//默认帧率
const defaultRatio: number = 60.0;
//默认单帧持续时间
const defaultTimeSpan = oneSecond / defaultRatio;

//游戏
abstract class Game {

    //抽象属性
    abstract canvas: HTMLCanvasElement;

    //更新
    abstract update(timespan: number): void

    //绘图
    abstract draw(): void

    //实时帧率
    ratioRealTime = defaultTimeSpan;

    //实时渲染的时间跨度
    timespanRealTime = defaultTimeSpan;//默认//16.66;

    //是否正在运行
    running = true;

    async run() {
        //主循环
        while (this.running) {
            //计时
            const start = new Date().getTime();
            //更新
            this.update(this.timespanRealTime);
            //绘图
            this.draw();
            //消耗的时间        
            const elapsed: number = new Date().getTime() - start;

            //需要等待时间
            let wait = defaultTimeSpan - elapsed;
            if (wait > 0) {
                await sleep(wait);
            }

            //设置时间跨度
            this.timespanRealTime = (wait > 0) ? (wait + elapsed) : elapsed;

            //帧率
            this.ratioRealTime = oneSecond / this.timespanRealTime;

        }
    }

}




//贪吃蛇
class Snake extends Game {

    //增加一个魔法特效
    sprites: Sprite[] = [new MagicSprite()];
    //抽象属性
    canvas: HTMLCanvasElement;

    constructor(canvas: string) {
        super();
        //加载资源
        this.canvas = window.document.getElementById(canvas) as HTMLCanvasElement;
    }

    update(timespan: number): void {
        //update更新逻辑
        for (let sp of this.sprites) {
            sp.update(timespan);
        }
    }

    draw(): void {
        
        //清理画布
        let ctx = this.canvas.getContext('2d');
        ctx.clearRect(0, 0, 860, 550);

        //重绘
        for (let sp of this.sprites) {
            sp.draw(this.canvas);
        }
    }

}

export default Snake;


